package com.hdw.job.batch.writer;

import com.hdw.common.base.mapper.BaseMapper;
import com.hdw.common.db.RoutingDataSource;
import com.hdw.common.util.DBUtil;
import com.hdw.common.util.SnowflakeIdWorker;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by liujunlei on 2021/5/25.
 */
@Component
@StepScope
public class NoPkInsertWriter implements ItemWriter {

    @Value("#{jobParameters['tableName']}")
    private String tableName;

    @Autowired
    BaseMapper baseMapper;

    @Override
    @RoutingDataSource(IdDb = DBUtil.DB_DW)
    public void write(List list) throws Exception {
        List<Map<String,Object>> mapList = (List<Map<String,Object>>)list;
        if(mapList!=null) {
            int nowSize=0,lastSize=0;
            int mapSize = mapList.get(0).keySet().size();
            int num = 2100/(mapSize+2)-1;
            for(Map<String,Object> map:mapList) {
                if(map.get("ID")==null) {
                    map.put("ID", SnowflakeIdWorker.getId());
                    map.put("DT_SYS_CRE",new Date());
                }
                nowSize++;
                if(nowSize%num==0) {
                    baseMapper.insertMapList(tableName,mapList.get(0),list.subList(lastSize,nowSize));
                    lastSize = nowSize;
                }
                if(nowSize==mapList.size() && nowSize!=lastSize) {
                    baseMapper.insertMapList(tableName,mapList.get(0),list.subList(lastSize,nowSize));
                }
            }
        }
    }
}
